package com.ecnu.web.controller.incubation;

import com.ecnu.common.core.controller.BaseController;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.TableDataInfo;
import com.ecnu.common.utils.OtherUtil;
import com.ecnu.common.utils.StringUtils;
import com.ecnu.system.domain.IncubationFactory;
import com.ecnu.system.domain.IncubationFile;
import com.ecnu.system.domain.dto.incubation.FactoryPageDTO;
import com.ecnu.system.domain.dto.incubation.FilePageDTO;
import com.ecnu.system.domain.dto.incubation.IncubationFactoryDTO;
import com.ecnu.system.domain.dto.incubation.IncubationFileDTO;
import com.ecnu.system.service.IIncubationFactoryService;
import com.ecnu.system.service.IIncubationFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * ecnu_二期_成果车间 前端控制器
 * </p>
 *
 * @author zdn
 * @since 2025-10-16
 */
@RestController
@Api(tags = "二期_成果车间")
@RequestMapping("/incubation")
@Validated//用来校验controller参数带@notblack类似的注解
public class IncubationController extends BaseController {
    @Autowired
    private IIncubationFactoryService incubationFactoryService;
    @Autowired
    private IIncubationFileService incubationFileService;

    private static LoginUser getProUser() {
        LoginUser loginUser = new LoginUser();
        //看情况是否需要优化--获取登录信息问题
        try {
            loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {

        }
        return loginUser;
    }

    /**
     *  转化车间
     * @param dto
     * @return
     */
    @ApiOperation(value = "保存")
    @PostMapping("/factory/edit")
//    @PreAuthorize("@ss.hasPermi('incubation:edit')")
    public AjaxResult save(@Valid @RequestBody IncubationFactoryDTO dto) {
        LoginUser loginUser = getLoginUser();
        dto.setSource("平台上传");
        return incubationFactoryService.edit(dto, loginUser);
    }

    @ApiOperation(value = "转化车间查询")
    @PostMapping("/factory/list")
    public TableDataInfo list(@RequestBody FactoryPageDTO dto) {
        LoginUser proUser = getLoginUser();
        return incubationFactoryService.listForIncubation(dto, proUser);
    }

    @ApiOperation(value = "解析页面查询")
    @PostMapping("/factory/listByAnalysis")
    public TableDataInfo listByAnalysis(@RequestBody FactoryPageDTO dto) {
        LoginUser proUser = getLoginUser();
        return incubationFactoryService.listForAnalysis(dto, proUser);
    }
//    @ApiOperation(value = "任务认领查询")
//    @PostMapping("/factory/listByClaim")
//    public TableDataInfo listByClaim(@RequestBody FactoryPageDTO dto) {
//        LoginUser proUser = getLoginUser();
//        return incubationFactoryService.listByClaim(dto, proUser);
//    }

    @ApiOperation(value = "删除")
    @PostMapping("/factory/del")
//    @PreAuthorize("@ss.hasPermi('incubation:del')")
    public AjaxResult del(@RequestBody String[] ids) {
        LoginUser loginUser = getLoginUser();
        try {
            List<IncubationFactory> incubationFactorys = Arrays.stream(ids)
                    .map(id -> {
                        IncubationFactory incubationFactory = new IncubationFactory();
                        incubationFactory.setId(id);
                        incubationFactory.setDelFlag("2");
                        incubationFactory.setUpdateUser(loginUser.getUserId().toString());
                        return incubationFactory;
                    })
                    .collect(Collectors.toList());
            return incubationFactoryService.updateBatchById(incubationFactorys) ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
        } catch (Exception e) {
            logger.error("成果删除错误" + e.getMessage());
            return AjaxResult.error("删除失败");
        }
    }

    @ApiOperation(value = "明细")
    @GetMapping("/factory/info")
    public AjaxResult info(@RequestParam
                               @NotBlank String id) {
        return incubationFactoryService.infoById(id);
    }

    /**
     * 文件管理
     */

    @ApiOperation(value = "对应成果文件管理")
    @PostMapping("/file/list")
    public TableDataInfo fileList(@RequestBody FilePageDTO dto) {
        try {
            return incubationFileService.List(dto);
        } catch (Exception e) {
            return OtherUtil.tableError("文件列表错误，请联系管理员");
        }
    }

    @ApiOperation(value = "保存文件")
    @PostMapping("/file/save")
//    @PreAuthorize("@ss.hasPermi('incubation:del')")
    public AjaxResult fileSave(@RequestBody List<IncubationFileDTO> dto) {
        LoginUser loginUser = getLoginUser();
        return incubationFileService.edit(dto, loginUser);
    }

    @ApiOperation(value = "删除文件")
    @PostMapping("/file/del")
//    @PreAuthorize("@ss.hasPermi('incubation:del')")
    public AjaxResult fileDel(@RequestBody String[] ids) {

        LoginUser loginUser = getLoginUser();
        try {
            List<IncubationFile> incubationFiles = Arrays.stream(ids)
                    .map(id -> {
                        IncubationFile incubationFile = new IncubationFile();
                        incubationFile.setId(id);
                        incubationFile.setDelFlag("2");
                        incubationFile.setUpdateUser(loginUser.getUserId().toString());
                        return incubationFile;
                    })
                    .collect(Collectors.toList());
            return incubationFileService.updateBatchById(incubationFiles) ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
        } catch (Exception e) {
            logger.error("成果删除错误" + e.getMessage());
            return AjaxResult.error("删除失败");
        }
    }

    @ApiOperation(value = "人工转化（暂时暂定，需要调整，需要和老师沟通）")
    @PostMapping("/factory/transform")
    public AjaxResult Transform(@RequestBody String[] ids) {
        LoginUser loginUser = getLoginUser();

        return incubationFactoryService.transform(ids,loginUser);
//        return null;
    }
    @ApiOperation(value = "成果字典抓取")
    @GetMapping("/factory/dictionary")
    public AjaxResult Dictionary() {

        return incubationFactoryService.dictionary();
//        return null;
    }
}
